package com.example.com.skills_utf8;

import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.renderscript.Sampler;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.app.util.Utils_Log;
import com.app.video.MyVideoCameraPreview;

import java.util.Timer;


//
public class _64_4Fragment extends Fragment {


    private final String TAG = _64_4Fragment.class.getSimpleName();


    MyVideoCameraPreview preview;
    Timer timer = new Timer();

    Handler handler = new Handler();


    // 手势监听
    GestureDetectorCompat gesturedetector ;
    MyGestureListener gestureListener = new MyGestureListener();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        final View view = inflater.inflate(R.layout.fragment_64_4, container, false);


        // 生成手势监听对象；
        gesturedetector = new GestureDetectorCompat(getActivity(), gestureListener);


        final FrameLayout layout_camera_content = (FrameLayout)view.findViewById(R.id.layout_camera_content);
        final ImageView iv = (ImageView) view.findViewById(R.id.iv_frame_box);

        preview = new MyVideoCameraPreview();
        final View iv_camera_content = (View)preview.init(getActivity());

        layout_camera_content.addView(iv_camera_content);

        preview.start();

        //
        iv_camera_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {


                float x = event.getX();  //相对于本身view的左上角的偏移值
                float y = event.getY();


                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    Utils_Log.e(TAG, "x: " + x + " y: " + y);
                    preview.SetAutoFoucs();


                    // 在屏幕绘制聚焦图案
                    int width = iv_camera_content.getWidth();
                    int height = iv_camera_content.getHeight();

                    int width_box = 256;
                    int height_box = 256;

                    // 本身就在屏幕坐标系下,无需转换
                    final int pos_x = (int) x; //width/2;
                    final int pos_y = (int) y; //height/2;

                    final int src_x = (int)width/2;
                    final int src_y = (int)height/2;


                    //
                    final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                    final Canvas canvas = new Canvas(bitmap);
                    final Paint paint = new Paint();
                    final Rect rect = new Rect();
                    rect.left = src_x - width_box / 2;
                    rect.top = src_y - height_box / 2;
                    rect.right = rect.left + width_box;
                    rect.bottom = rect.top + height_box;


                    paint.setColor(Color.BLUE);
                    paint.setStyle(Paint.Style.STROKE);
                    paint.setStrokeWidth(5);
                    canvas.drawRect(rect, paint);

                    final Paint paint_alpha = new Paint();
                    paint_alpha.setARGB(0,0,0,0);
                    paint_alpha.setStyle(Paint.Style.STROKE);
                    paint_alpha.setStrokeWidth(5);

                    /*
                    Matrix matrix = new Matrix();
                    matrix.postTranslate(pos_x - src_x, pos_y - src_y);
                    RectF rect_dest = new RectF();
                    rect_dest.set(rect);
                    matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                    canvas.drawRect(rect_dest, paint);
                    */

                    final RectF rect_last = new RectF();
                    final RectF rect_last1 = new RectF();
                    final RectF rect_last2 = new RectF();
                    final RectF rect_last3 = new RectF();
                    rect_last.set(rect);
                    rect_last1.set(rect);
                    rect_last2.set(rect);
                    rect_last3.set(rect);

                    {

                        final Point point = new Point();
                        //final Matrix matrix = new Matrix();
                        int time = 5000;

                        AnimationSet animation_set = new AnimationSet(true);



                        /*
                        int[][] value = new int[2][2];
                        value[0][0] = 0;
                        value[0][1] = pos_x - src_x;
                        value[1][0] = 0;
                        value[1][1] = pos_y - src_y;
                        */
                        ObjectAnimator anim_x = ObjectAnimator//
                                .ofInt(iv, "zhy", 0, pos_x - src_x)
                                //.ofMultiInt(iv, "zhy", value)//
                                .setDuration(time);//
                        anim_x.start();
                        anim_x.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {

                                canvas.drawRect(rect_last, paint_alpha);


                                int t = (int) animation.getAnimatedValue();
                                point.x = t;
                                //float delta = pos_x - src_x;
                                Utils_Log.e(TAG, "t: " + t);
                                //Utils_Log.e(TAG, "result: "+delta*t);

                                Matrix matrix = new Matrix();
                                matrix.postTranslate(point.x, point.y);
                                RectF rect_dest = new RectF();
                                rect_dest.set(rect);
                                matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                                canvas.drawRect(rect_dest, paint);


                                rect_last.set(rect_dest);

                                iv.setImageBitmap(bitmap);

                            }
                        });


                        ObjectAnimator anim_y = ObjectAnimator//
                                .ofInt(iv, "zhy", 0, pos_y - src_y)
                                .setDuration(time);//
                        anim_y.start();
                        anim_y.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {

                                canvas.drawRect(rect_last1, paint_alpha);

                                int t = (int) animation.getAnimatedValue();
                                point.y = t;
                                Utils_Log.e(TAG, "t: " + t);

                                Matrix matrix = new Matrix();
                                matrix.postTranslate(point.x, point.y);
                                RectF rect_dest = new RectF();
                                rect_dest.set(rect);
                                matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                                canvas.drawRect(rect_dest, paint);

                                rect_last1.set(rect_dest);

                                iv.setImageBitmap(bitmap);

                            }
                        });


                        /*
                        final PointF point_scale = new PointF();
                        float scale_x_delat = 2;
                        ObjectAnimator scale_x = ObjectAnimator//
                                .ofFloat(iv, "zhy", scale_x_delat, 0)
                                .setDuration(time);//
                        scale_x.start();
                        scale_x.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {

                                //canvas.drawRect(rect_last2, paint_alpha);

                                float t = (float) animation.getAnimatedValue();
                                point_scale.x = t;
                                Utils_Log.e(TAG, "t: " + t);

                                Matrix matrix = new Matrix();
                                matrix.postScale(point_scale.x, point_scale.y);
                                RectF rect_dest = new RectF();
                                rect_dest.set(rect);
                                matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                                canvas.drawRect(rect_dest, paint);

                                //rect_last2.set(rect);
                                iv.setImageBitmap(bitmap);

                            }
                        });


                        float scale_y_delat = 2;
                        ObjectAnimator scale_y = ObjectAnimator//
                                .ofFloat(iv, "zhy", scale_y_delat, 0)
                                .setDuration(time);//
                        scale_y.start();
                        scale_y.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {

                                //canvas.drawRect(rect_last3, paint_alpha);

                                float t = (float) animation.getAnimatedValue();
                                point_scale.y = t;
                                Utils_Log.e(TAG, "t: " + t);

                                Matrix matrix = new Matrix();
                                matrix.postScale(point_scale.x, point_scale.y);
                                RectF rect_dest = new RectF();
                                rect_dest.set(rect);
                                matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                                canvas.drawRect(rect_dest, paint);

                                //rect_last3.set(rect);
                                iv.setImageBitmap(bitmap);

                            }
                        });
                        */





                        iv.setImageBitmap(bitmap);


                        /*
                        ScaleAnimation scale = new ScaleAnimation(0,0,0,0);
                        TranslateAnimation trans = new TranslateAnimation(0,0,0,0);

                        animation_set.addAnimation(scale);
                        animation_set.addAnimation(trans);
                        animation_set.setDuration(500);
                        animation_set.start();
                        */



                        /*
                        // 放置一个插值器
                        ValueAnimator valueanimator = new ValueAnimator();
                        valueanimator.ofFloat( 0, Math.abs(pos_x-src_x) );
                        valueanimator.setInterpolator( new LinearInterpolator() );
                        valueanimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {

                                float t = (Float) animation.getAnimatedValue();
                                Utils_Log.e(TAG, "t: "+t);


                                Matrix matrix = new Matrix();
                                matrix.postTranslate(src_x + t, src_y + t);
                                RectF rect_dest = new RectF();
                                rect_dest.set(rect);
                                matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                                canvas.drawRect(rect_dest, paint);

                            }
                        });
                        valueanimator.start();
                        */


                        /*
                        // 平移动画；
                        Animation animation = new TranslateAnimation( Animation.ABSOLUTE, src_x, Animation.ABSOLUTE, pos_x,
                                Animation.ABSOLUTE, src_y, Animation.ABSOLUTE, pos_y
                                );
                        animation.setDuration(1500);


                        AnimationSet animationset = new AnimationSet(true);
                        animationset.addAnimation( animation );


                        iv.startAnimation(animationset);
                        */


                    }





                    /*
                    // 根据手指点击来设置目标；物体快速平移和缩放过去；
                    Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.scale_and_alpha);
                    iv.startAnimation(animation);
                    */

                }


                return gesturedetector.onTouchEvent(event);
            }
        });




        preview.mycamera.printSupportFocusMode();
        preview.mycamera.printSupportFlashMode();
        preview.mycamera.printZoomRatios();;


        int MaxZoom = preview.mycamera.GetMaxZoom();
        SeekBar sb_zoom = (SeekBar)view.findViewById(R.id.sb_zoom);
        sb_zoom.setMax(MaxZoom);
        sb_zoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                preview.mycamera.SetZoom(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        //ProgressBar bar = new ProgressBar(getActivity());




        return view;

    }


    @Override
    public void onPause() {
        super.onPause();
        //System.out.println("onPause");

        preview.close();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //System.out.println("onDestroy");

        //preview.close();
    }



    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            Utils_Log.e(TAG, "onDoubleTap");

            // 使相机变焦，拉近
            if(preview.mycamera.GetZoom() == preview.mycamera.GetMaxZoom() ){

                new Thread(new Runnable() {

                    int progress = preview.mycamera.GetMaxZoom();

                    public void run() {
                        while (progress > 0) {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }

                            // Update the progress bar
                            handler.post(new Runnable() {
                                public void run() {
                                    preview.mycamera.SetZoom(progress--);
                                }
                            });
                        }
                    }
                }).start();

            }
            else{

                new Thread(new Runnable() {

                    int MaxZoom = preview.mycamera.GetMaxZoom();
                    int progress = 0;

                    public void run() {
                        while (progress < MaxZoom) {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }

                            // Update the progress bar
                            handler.post(new Runnable() {
                                public void run() {
                                    preview.mycamera.SetZoom(progress++);
                                }
                            });
                        }
                    }
                }).start();

            }




            return super.onDoubleTap(e);
        }


        @Override
        public boolean onDown(MotionEvent e) {
            Utils_Log.e(TAG, "onDown");
            return true;        // 返回true，使后续能接着处理
        }

    }





}
